import Vue from "vue";
import Sortable from "sortablejs";
import dbl from "@/utils/dbl";
import store from "@/store/index.js";
import { getUserRouter, resetRouter } from "@/router/index.js";

const mixin = {
  data() {
    return {
      $userInfo: {},
      $currentUserInfo: {}, // 下一级详情用到的userInfo
      $localPageSteps: ""
    };
  },
  created() {
    
    this.$userInfo = store.getters["user/userInfo"]||{};
    this.$currentUserInfo = store.getters["user/currentUserInfo"];
    this.$localPageSteps = store.getters["user/localPageSteps"] || [];
    // console.log('this.$currentUserInfo', this.$currentUserInfo)
  },
  computed: {
    stepsLocationName() {
      let localPage = store.getters["user/localPageSteps"] || [];
      return localPage.map(i=>i.orgName)?.join("/")
    },
  },
  methods: {
    $showAuthElement() {
      return true;
    },
    getParameter(key) {
      return this.$route.query[key];
    },
    link(name, query) {
      this.$router.push({ name, query });
    },
    $path(path) {
      return this.$PathHandler.getApiPath(path);
    },
    $image(path) {
      return this.$PathHandler.getImagePath(path);
    },
    $video(path) {
      return this.$PathHandler.getVideoPath(path);
    },
    inArray(value, values) {
      return values.indexOf(value) >= 0;
    },
    $in(value, values) {
      return values.indexOf(value) >= 0;
    },

    $enum(values, value, defaultValue) {
      if (!values) {
        return {};
      }
      if (!values[value]) {
        return values[defaultValue];
      } else {
        return values[value];
      }
    },

    $dictValue(value) {
      if (!this.dict) return value;
      for (let key in this.dict) {
        value = value.replace(new RegExp(`{${key}}`, "g"), this.dict[key]);
      }
      return value;
    },

    $isEmpty(v) {
      return v == null || v == undefined;
    },
    $isNotEmpty(v) {
      return !this.$isEmpty(v);
    },
    $inStatus(statusMap, e, values) {
      if (!e || !values) {
        return false;
      }
      let v = this.$isNotEmpty(e["status"])
        ? statusMap[e["status"]]
        : statusMap[e];
      return v && values.indexOf(v.code) >= 0;
    },
    $notInStatus(statusMap, e, values) {
      if (!e || !values) {
        return false;
      }
      let v = this.$isNotEmpty(e["status"])
        ? statusMap[e["status"]]
        : statusMap[e];
      return v && values.indexOf(v.code) < 0;
    },

    $checkResNotNull(res, quiet, message) {
      if (res && res.body != undefined && res.body != null) {
        return true;
      } else {
        if (!quiet) {
          this.$message.error(message ? message : "服务端返回数据有误！");
        }
        return false;
      }
    },

    $error() {
      if (this.loading) {
        this.loading = false;
      }
      if (this.table && this.table.loading) {
        this.table.loading = false;
      }
      if (this.loginLoading) {
        this.loginLoading = false;
      }
    },

    $loadEntity(method, queryIdKey, pathIdKey, callback) {
      let id = this.getParameter(queryIdKey);
      if (!id) {
        callback && callback();
        return;
      }
      let param = { path: {} };
      param.path[pathIdKey] = id;
      return method.call(null, param, callback);
    },

    loadEntity(method, idKey, callback) {
      let id = this.getParameter(idKey);
      if (!id) {
        callback && callback();
        return;
      }
      let param = { path: {} };
      param.path[idKey] = id;
      return method.call(null, param, (res) => {
        if (res && res.body) {
          callback(res);
        } else {
          this.$message.error("服务端返回的数据有误");
          callback(res);
        }
      });
    },

    $handleQuery(loadTable) {
      if (loadTable) {
        loadTable();
      } else {
        this.loadTable();
      }
    },
    $handleInputQuery(loadTable, table) {
      if (table && table.page) {
        table.page.current = 1;
      } else {
        this.table.page.current = 1;
      }
      this.$handleQuery(loadTable);
    },

    $deleteRow(method, idKey, idValue, success, error) {
      this.$confirm("即将删除此条数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          let param = { path: {} };
          param.path[idKey] = idValue;
          method.call(
            null,
            param,
            (res) => {
              this.$message({
                type: "success",
                message: "删除成功!",
              });
              success && success(res);
            },
            error
          );
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    $removeByKey(list, key, value) {
      //不可以使用lodash.remove
      let o = this.$findByKey(list, key, value);
      if (list && o) {
        list.splice(list.indexOf(o), 1);
      }
    },
    $findByKey(list, key, value) {
      if (list && key && value) {
        let param = {};
        param[key] = value;
        return this.$lodash.find(list, param);
      } else {
        return null;
      }
    },

    $guideModifyCheck(entity, guide) {
      this.$guideCheck(
        entity,
        guide,
        () => {
          this.$router.push({
            name: guide.modify.link,
            query: guide.modify.param(guide.entity),
          });
        },
        () => {
          this.$message.error("检查编辑项出错，请稍候重试。");
        }
      );
    },

    $guideDeleteCheck(entity, guide) {
      this.$guideCheck(
        entity,
        guide,
        () => {
          guide.delete.visible = true;
        },
        () => {
          this.$message.error("检查删除项出错，请稍候重试。");
        }
      );
    },
    $guideCheck(entity, guide, succes, error) {
      guide.entity = entity;
      let checkOptions = guide.check;
      let guideOptions = guide.warn;

      let method = checkOptions.method;
      let param = checkOptions.param(entity);
      method.call(
        null,
        param,
        (res) => {
          let codes = checkOptions.adapter(res, true);
          if (!codes || codes.length == 0) {
            succes && succes(res);
          } else {
            guideOptions.codes = codes;
            guideOptions.visible = true;
          }
        },
        (err) => {
          error && error(err);
        }
      );
    },

    $guideDelete(guide) {
      let checkOptions = guide.check;
      let guideOptions = guide.warn;
      let deleteOptions = guide.delete;
      deleteOptions.loading = true;
      let param = deleteOptions.param(guide.entity);
      deleteOptions.method
        .call(
          null,
          param,
          (res) => {
            deleteOptions.loading = false;
            deleteOptions.visible = false;
            let codes = checkOptions.adapter(res, false);
            if (!codes || codes.length == 0) {
              this.$message.success("删除成功!");
              deleteOptions.callback.success &&
                deleteOptions.callback.success(res);
            } else {
              guideOptions.codes = codes;
              guideOptions.visible = true;
            }
          },
          deleteOptions.callback.error
        )
        .catch(() => {
          deleteOptions.loading = false;
        });
    },

    $mergeByKey(pa, pb, key) {
      //防止pa与pb内部重复
      //覆盖逻辑：先进原则
      let result = [];
      if (pa) {
        for (const p of pa) {
          let exist = this.$lodash.find(result, (o) => {
            return o[key] == p[key];
          });
          if (!exist) {
            result.push(p);
          }
        }
      }
      if (pb) {
        for (const p of pb) {
          let exist = this.$lodash.find(result, (o) => {
            return o[key] == p[key];
          });
          if (!exist) {
            result.push(p);
          }
        }
      }
      return result;
    },

    $columnKey() {
      return null;
      // return new Date().getTime() + "" + (Math.random() * 10000000).toFixed(0);
    },

    $handleQueryParam() {
      let menuId = this.getParameter("menuId");
      if (!menuId) {
        console.log("menuId should not be empty!");
        return {};
      }
      return {
        body: {
          menuID: menuId,
          createdBy: this.$userInfo.phone,
        },
      };
    },

    $handleFormValidate(name, success, ...args) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          success && success(...args);
        } else {
          this.$message.error("请检查表单中的数据是否完整和正确");
          return false;
        }
      });
    },

    $invokeSave(param, idKey, addMethod, modifyMethod, callback, quiet) {
      let hasEntityId = param.body[idKey];
      let method = hasEntityId ? modifyMethod : addMethod;
      console.log("invoke:", hasEntityId ? "modify" : "add", param);
      return method.call(
        null,
        param,
        (res) => {
          if (!quiet) {
            if (res && res.data) {
              this.$message.success("保存成功");
              if (param.next) {
                console.log("auto router to list: ", param.next);
                this.$closeTagView();
                this.link(param.next);
              }
            } else {
              this.$message.error("服务端返回数据异常");
            }
          }
          callback && callback(res);
        },
        this.$error
      );
    },
    $closeTagView() {
      this.$store.dispatch("delView", this.$route);
    },
    $initDragTable(table, entity, name, success) {
      console.log(table, "123456");
      if (!table || !table.$el) {
        return false;
      }
      const el = table.$el.querySelectorAll(
        ".el-table__body-wrapper > table > tbody"
      )[0];
      this.sortable = Sortable.create(el, {
        ghostClass: "sortable-ghost", // Class name for the drop placeholder,
        setData: function (dataTransfer) {
          // to avoid Firefox bug
          // Detail see : https://github.com/RubaXa/Sortable/issues/1012
          dataTransfer.setData("Text", "");
        },
        animation: 150,
        onUpdate: (evt) => {
          if (!entity || !name) {
            success && success(evt);
            return;
          }
          let list = entity[name];
          const targetRow = list.splice(evt.oldIndex, 1)[0];
          list.splice(evt.newIndex, 0, targetRow);
          if (success) {
            success(list);
          } else {
            entity[name] = [];
            this.$nextTick(() => {
              entity[name] = list;
            });
          }
        },
      });
    },
    $stopDragTable() {
      this.sortable.destroy();
    },
    async $existAd(id, phone) {
      // 是否存在单位
      let res = await this.$api.AdminController.exist({ body: { id, phone } });
      if (res.code == 0) {
        return res;
      }
      return false;
    },
    async $existPeople(id, phone) { // 是否存在人员
      let res = await this.$api.UserController.exist({ body: { id, phone } });
      if (res.code == 0) {
        return res;
      }
      return false;
    },
    // 点击进入下一级详情
    handleLevelDetail($scope) {
      let params = {
        createdBy: this.$userInfo.phone,
        phone: $scope.row.phone,
        menuID: this.getParameter("menuId"),
        orgId: $scope.row.orgId,
        orgName: $scope.row.orgName
      };
      this.$api.OrgController.detail({ body: params }, async (res) => {
        if (res.code == 0) {
          // 保存到本地
          let localPage = await store.getters["user/localPageSteps"] || [];
          await store.commit("user/setLocalPageSteps", localPage.concat(params))
          // dbl.set("localPageSteps", localPage.concat(params));
          // console.log('dbl.get("localPageSteps")', dbl.get("localPageSteps"))
          let body = res.data;
          let userRouters = getUserRouter(
            body ? body.menuPermission : "",
            body
          );
          await store.commit("SET_ROUTERS", userRouters);
          await store.commit("user/setCurrentUserInfo", body);
          resetRouter();
          let menu = userRouters[0].children[0];
          console.log("menu", menu);
          // this.$router.push('/jydw-list?menuId=1000000010')
          this.link(menu.name, menu.meta.query);
        }
      });
    },
    // 点击返回上一级详情
    async handlePreLevel() {
      
      let localPage = this.$localPageSteps;
      if (localPage.length > 1) {
        this.$api.OrgController.detail(
          { body: localPage[localPage.length - 2] },
          async (res) => {
            if (res.code == 0) {
              let body = res.data;
              let userRouters = getUserRouter(
                body ? body.menuPermission : "",
                body
              );
              await store.commit("SET_ROUTERS", userRouters);
              await store.commit("user/setCurrentUserInfo", body);
              let aa = localPage.pop();
              // console.log("localPageSteps", localPage)
              await store.commit("user/setLocalPageSteps", localPage)
              // dbl.set("localPageSteps", localPage)
              resetRouter();
              let menu = userRouters[0].children[0];
              // console.log("menu", menu);
              // this.$router.push('/jydw-list?menuId=1000000010')
              this.$router.push({
                name: menu.name,
                query: {...menu.meta.query, requestId: new Date().getTime()},
                replace: true,
              });
              // this.link(menu.name, menu.meta.query);
            }
          }
        );
      } else {
        // 返回第一级
        let body = this.$userInfo;
        let userRouters = getUserRouter(
          body ? body.menuPermission : "",
          body
        );
        await store.commit("SET_ROUTERS", userRouters);
        await store.commit("user/setCurrentUserInfo", "");
        await store.commit("user/setLocalPageSteps", "")
        // dbl.set("localPageSteps","")
        resetRouter();
        let menu = userRouters[0].children[0];
        console.log("menu", menu);
        // this.$router.push('/jydw-list?menuId=1000000010')
        this.$router.push({
          name: menu.name,
          query: {...menu.meta.query, requestId: new Date().getTime()},
          replace: true,
        });
        // this.link(menu.name, menu.meta.query);
      }
    },
  },
};

Vue.mixin(mixin);
